//
//  BanBu_EmoKeyboard.m
//  Koochat
//
//  Created by Wang Xj on 14-4-9.
//
//

#import "BanBu_EmoKeyboard.h"
#import "BanBu_EmoManger.h"
#import "BanBu_SmileViewAPI.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "SCGIFImageView.h"

#define DeleteTag 999

@implementation BanBu_EmoKeyboard

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initWithKeyboard];
        
        [self initWithEmoType];
        
        _defaultEmoScrollView.hidden = NO;
    }
    return self;
}

-(void)initWithEmo
{
    [self initWithKeyboard];
    
    [self initWithEmoType];
    
    _defaultEmoScrollView.hidden = NO;
}


- (void)dealloc
{
    [_emoInfoDic release],_emoInfoDic = nil;
    [_inputedStr release],_inputedStr = nil;
    [_keyboardScrollView release];
    [_emoTypeScrollView release];
    [_pageControl release];
    [_defaultEmoScrollView release];
    [_characterScrollView release];
    [_EmoScrollView release];
    [_backgroundImageView release];
    [_showBigView release];
    [_BigView release];
    [super dealloc];
}

#pragma mark - 初始化键盘

//初始化表情种类按钮
-(void)initWithEmoType
{
    //获取下载的表情的种类信息
    NSDictionary * downloadEmoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:downloadEmoDic.allValues];
    
    [array sortUsingFunction:compare context:NULL];
    
    self.emoArr = array;
    
    [_emoTypeScrollView setContentSize:CGSizeMake(240+60*self.emoArr.count, 40)];
    
    //添加小表情、收藏、字符三种表情
    for (int i = 0 ;i < self.emoArr.count; i++)
    {
        NSDictionary * oneEmoInfo = [self.emoArr objectAtIndex:i];
        
        //添加button
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(180 + i*60, 0, 60, 40);
        [button setTitle:[oneEmoInfo valueForKey:KeyName] forState:UIControlStateNormal];
        button.tag = 10000+i;
        
        [button addTarget:self action:@selector(changeEmoType:) forControlEvents:UIControlEventTouchUpInside];
        
        [_emoTypeScrollView addSubview:button];
    }
}

//初始化键盘内容
-(void)initWithKeyboard
{
    //默认表情
    [self initWithDefaultEmo];
    
    //字符
    [self initWithCharater];
    
    //收藏
    //下载的表情，两者共用一个view
//    [self initWithCustEmo:];
}

//默认表情
-(void)initWithDefaultEmo
{
    NSInteger page = 0;
    _pageControl.frame = CGRectMake(0, 154, 320, 10);
    _pageControl.numberOfPages = 2;
    _pageControl.currentPage = 0;
    _pageControl.numberOfPages = 2;
    
    _defaultEmoScrollView.contentSize= CGSizeMake(320*_pageControl.numberOfPages, 140);

    NSArray  *smileArr = [NSArray arrayWithObjects:@"打怪兽",@"嘟嘟嘴",@"多变",@"饿了",@"高兴",@"歌王",@"好烦啊",@"加油",@"惊讶",@"可爱",@"可怜",@"麦霸",@"怒火",@"饶命",@"撒娇",@"睡觉",@"痛苦",@"羞羞脸",@"阴谋",@"眨眼",@"发大财",@"喷饭",@"炸飞了",@"凄凉",@"T台秀",@"读书",@"扭屁股",@"舞蹈",@"得意",@"运动",@"救命",@"滚远点",@"江南舞",@"走你", nil];
    
    for(int i=0; i<[smileArr count]; i++)
    {
        NSString *imageName = [NSString stringWithFormat:@"%@",[smileArr objectAtIndex:i]];
        NSString *path=[[NSBundle mainBundle]pathForResource:imageName ofType:@"gif"];
        SCGIFImageView *gif=[[SCGIFImageView alloc]initWithGIFFile:path];
        gif.userInteractionEnabled=YES;
        gif.frame=CGRectMake(320*page+10+52*(i%6), 50*(i/6-3*page), 35, 35);
        gif.backgroundColor=[UIColor blackColor];
        gif.tag=i;
        
        NSLog(@"gif.frame:%@",NSStringFromCGRect(gif.frame));
        
        //加一个手势 让他触发方法
        UITapGestureRecognizer *tapGester=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnPress:)];
        [gif addGestureRecognizer:tapGester];
        [tapGester release];
        [_defaultEmoScrollView addSubview:gif];
        [gif release];
        
        if(i>16 && !page)
            page = 1;
        if(i>34)
        {
            page = 2;
        }
    }
    
    [_keyboardScrollView addSubview:_defaultEmoScrollView];
}

//字符
-(void)initWithCharater
{
    NSInteger page = 0;
    _pageControl.frame = CGRectMake(0, 154, 320, 10);
    _pageControl.numberOfPages = 3;
    _pageControl.currentPage = 0;
    
    _characterScrollView.contentSize= CGSizeMake(320*3, 140);
    
    NSArray *titles = [NSArray arrayWithObjects:@"T_T",@"⊙ ⊙",@"~~>_<~~",@"^_~",@"*o*",@":p",@"@_@",@"<@_@>",@"o_o",@"^o^",@"O_O",@"-_-",@"^_^",@"＿.,＿",@"^v^",@"^^v",@"(^-^)",@"=_=^",@"=^_^=",@"*^_^*",@"=_=",@"+_+",@"?_?",@"$_$",@"~_~",@"T^T",@">o<",@"e_e",@"－_－#",@"－_－b",@"－_－^",@">_<",@"－O－",@"O(∩_∩)O~",@"(*^__^*)",@"\(^o^)/~",@"( ⊙o⊙ )",@"╭(╯^╰)╮",@"（¯『¯）",@"o(≥v≤)o~~",@"~(@^_^@)~",@"(^ω^)",@"(*^◎^*)",@"(+﹏+)~",@"o(╯□╰)o",@"╭∩╮",@"-_-|||",@"( ^_^ )/~~",@"(ˉ(∞)ˉ)" ,nil];
    
    for(int i=0; i<48; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(320*page+80*(i%4),34*(i/4-4*page), 79,33);
        [button setBackgroundImage:[UIImage imageNamed:@"button_emotion.png"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [button setTitle:[titles objectAtIndex:i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;
        [_characterScrollView addSubview:button];
        if(i>14 && !page)
            page = 1;
        if(i>30)
        {
            page = 2;
        }
    }
    
    [_keyboardScrollView addSubview:_characterScrollView];
}

//收藏、下载的表情
-(void)initWithCustEmo:(NSDictionary *)emoInfoDic
{
    NSInteger imagCount = [[emoInfoDic valueForKey:KeyCount] integerValue];
    _EmoScrollView.contentSize = CGSizeMake(320*ceilf(imagCount/8.0), 216);
    _EmoScrollView.pagingEnabled = YES;
    _pageControl.numberOfPages = ceilf(imagCount/8.0);
    
    CGRect frame = CGRectZero;
    NSInteger page = 0;
    for (int i = 0;i<imagCount;i++)
    {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
        frame = imageView.frame;
        frame.origin.x = 76*(i%4) + page*320 +16;
        frame.origin.y = 90*((i-page*8)/4)+10;
        imageView.frame = frame;
        
        imageView.userInteractionEnabled = YES;
        imageView.backgroundColor = [UIColor clearColor];
        imageView.tag = 10001+i;
        
        //添加手势
        UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showBigImage:)];
        [imageView addGestureRecognizer:longPress];
        [longPress release];
        
        //查缓存，没有缓存时下载并显示
        NSString * imageName = [NSString stringWithFormat:@"%d.jpg",i+1];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[emoInfoDic valueForKey:KeyPath],imageName];
        
        [imageView setImageWithUrlString:imageUrl withFolderName:[emoInfoDic valueForKey:KeyName] withImageName:imageName];
        
        [_EmoScrollView addSubview:imageView];
        if ((i+1)%8==0)
        {
            page += 1;
        }
    }
}
#pragma mark -切换不同表情时
//切换默认键盘：表情、收藏、符号
- (IBAction)changeDefaultKeyboard:(UIButton *)sender
{
    _emoInfoDic = nil;
}


//切换下载表情键盘
-(void)changeEmoType:(UIButton *)sender
{
    int index = self.tag - 10000;
    
    //选择的表情是
    NSDictionary * selectedEmo = [self.emoArr objectAtIndex:index];
    
    //显示选中的view
    [self setSelectedEmo:selectedEmo];
}

//设置选中表情键盘
-(void)setSelectedEmo:(NSDictionary *)emoDic
{
    _emoInfoDic = emoDic;
    
    NSInteger count = [[emoDic valueForKey:KeyCount] integerValue];
    NSInteger page = 0;
    _pageControl.frame = CGRectMake(0, 154, 320, 10);
    _pageControl.numberOfPages = ceil(count/8.0);
    _pageControl.currentPage = 0;

    self.EmoScrollView = [[UIScrollView alloc]initWithFrame:_emoTypeScrollView.frame];
    _EmoScrollView.delegate = self;
    _EmoScrollView.backgroundColor = [UIColor clearColor];
    _EmoScrollView.showsHorizontalScrollIndicator = NO;
    _EmoScrollView.pagingEnabled = YES;
    [_EmoScrollView setContentSize:CGSizeMake(320*_pageControl.numberOfPages, 175)];
    
    for(int i=0; i < count; i++)
    {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(320*page+80*(i%4), 10+80*((i%8)/4), 70, 70)];
        imageView.userInteractionEnabled = YES;
        
        NSString * imageName = [NSString stringWithFormat:@"%d.gif",i+1];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[emoDic valueForKey:KeyPath],imageName];
        [imageView setImageWithUrlString:imageUrl withFolderName:[emoDic valueForKey:KeyName] withImageName:imageName];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnPress:)];
        [imageView addGestureRecognizer:tap];
        [tap release];
        
        UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showBigImage:)];
        [imageView addGestureRecognizer:longPress];
        [longPress release];
        
        [_EmoScrollView addSubview:imageView];
    }
    _EmoScrollView.hidden = NO;
}

//发送
- (IBAction)sendEmo:(UIButton *)sender
{
    
}

#pragma mark - 表情键盘的代理处理
//发送：默认表情
-(void)btnPress:(UITapGestureRecognizer *)tap
{
    NSString *inputStr=nil;
    
    NSArray  *smileArr = [NSArray arrayWithObjects:@"打怪兽",@"嘟嘟嘴",@"多变",@"饿了",@"高兴",@"歌王",@"好烦啊",@"加油",@"惊讶",@"可爱",@"可怜",@"麦霸",@"怒火",@"饶命",@"撒娇",@"睡觉",@"痛苦",@"羞羞脸",@"阴谋",@"眨眼",@"发大财",@"喷饭",@"炸飞了",@"凄凉",@"T台秀",@"读书",@"扭屁股",@"舞蹈",@"得意",@"运动",@"救命",@"滚远点",@"江南舞",@"走你", nil];
    inputStr=[smileArr objectAtIndex:tap.view.tag];
    
    if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
        [_delegate banBu_SmileView:self didInputSmile:inputStr isDelete:NO type:1];
}

//发送：字符消息
- (void)btnPressed:(UIButton *)button
{
    if(button.tag == DeleteTag)
    {
        if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
            [_delegate banBu_SmileView:self didInputSmile:nil isDelete:YES type:0];
    }
    else
    {
        NSString *inputStr = nil;
        inputStr = button.titleLabel.text;
        [_inputedStr addObject:inputStr];
        if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
            [_delegate banBu_SmileView:self didInputSmile:inputStr isDelete:NO type:0];
        
    }
}

#pragma mark - 预览大图
//长按缩略图时显示大图
-(void)showBigImage:(UILongPressGestureRecognizer *)gesture
{
    //先判断点的是哪个缩略图
    CGPoint locationPoint = [gesture locationInView:_EmoScrollView];
    NSInteger x = (int)locationPoint.x %320;
    NSInteger y = locationPoint.y;
    NSInteger tagIndex = 10001;
    
    if (x < 75)//第一列
    {
        x = 10 +100;//100是大图的宽的一半，x，y是大图的中心点坐标
        tagIndex += _pageControl.currentPage*8;
    }
    else if (x<92+60)//第二列
    {
        x = 22 +100;
        tagIndex += _pageControl.currentPage*8 + 1;
    }
    else if (x< 168+60)//第三列
    {
        x = 98 +100;
        tagIndex += _pageControl.currentPage*8 + 2;
    }
    else//第四列
    {
        x = 110 +100;
        tagIndex += _pageControl.currentPage*8 + 3;
    }
    
    if (y<70)//第一行
    {
        y = 190;
    }
    else//第二行
    {
        y = 280;
        tagIndex += 4;
    }
    
    if (x <= 110)//在左边时
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_left.png"];
    }
    else if (x >= 210)//
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_right.png"];
    }
    else
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_middle.png"];
    }
    
    if (((int)_showBigView.center.x != x) || ((int)_showBigView.center.y != y))
    {
        //去下载大图
        _showBigView.center = CGPointMake(x, y);
        NSString * imageName = [NSString stringWithFormat:@"%d.gif",tagIndex-10000];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[_emoInfoDic valueForKey:KeyPath],imageName];
        [_BigView setImageWithUrlString:imageUrl withFolderName:[_emoInfoDic valueForKey:KeyName] withImageName:imageName];
    }
    
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            _showBigView.hidden = NO;
        }
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            [_BigView setImageWithURL:nil];
            _showBigView.hidden = YES;
            gesture.view.backgroundColor = [UIColor clearColor];
        }
        default:
            break;
    }
}

@end
